package _interview150;

import java.util.List;

/**
 * 120. 三角形最小路径和
 */
public class No120 {
    private List<List<Integer>> triangle;
    private int[][] cache;

    public int minimumTotal(List<List<Integer>> triangle) {
        this.triangle = triangle;
        int n = triangle.size();
        cache = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                cache[i][j] = Integer.MIN_VALUE;
            }
        }
        return dfs(0, 0);
    }

    private int dfs(int i, int j) {
        if (i >= triangle.size()) return 0;
        else if (j >= triangle.get(i).size()) return Integer.MAX_VALUE / 2;
        else if (cache[i][j] != Integer.MIN_VALUE) return cache[i][j];
        else return cache[i][j] = triangle.get(i).get(j) + Math.min(dfs(i + 1, j), dfs(i + 1, j + 1));
    }
}
